package com.ztjava.weixin.service;

import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.core.client.Client;
import com.ztjava.weixin.model.message.MessageReply;
import com.ztjava.weixin.model.message.MessageRule;

public class MessageService extends BaseService{
	/*************
	 *Reply分页
	**************/
	public Page<MessageReply> getReplyPage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
		new String[]{"name",like,"name"}				,new String[]{"type",eq,"type"}				,new String[]{"enable_flag",eq,"enable_flag"}			};
		Page<MessageReply> pd = MessageReply.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+MessageReply.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"type","WEIXIN_MESSAGE_REPLY_TYPE"}		, new String[]{"enable_flag","ENABLE_FLAG"});
		return pd;
	}
	/*************
	 *Rule分页
	**************/
	public Page<MessageRule> getRulePage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
		new String[]{"type",eq,"type"}		,new String[]{"reply_id",eq,"reply_id"}	};
		Page<MessageRule> pd = MessageRule.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+MessageRule.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"type","WEIXIN_MESSAGE_RULE_TYPE"});
		return pd;
	}
	public void deleteReply(Integer id){
		Db.update("delete from "+MessageReply.tablename+" where id=?",id);
		Db.update("delete from "+MessageRule.tablename+" where reply_id=?",id);
	}
	
	public MessageReply getReplyCache(Integer id){
		return MessageReply.dao.findFirstByCache(Constant.R_PRE+"WEIXIN:MESSAGE:REPLY", id.toString(), "select * from "+MessageReply.tablename+" where id=?",id);
	}

	public void loadRuleCache(){
		List<MessageRule> ruleList = MessageRule.dao.find("select * from "+MessageRule.tablename+" where enable_flag='T'");
		Cache cache = Redis.use();
		cache.del(Constant.R_PRE+"WEIXIN:MESSAGE:RULE");
		for(int i=0;i<ruleList.size();i++){
			String key =  ruleList.get(i).getStr("type")+"_";
			if(ruleList.get(i).getStr("value")!=null){
				key = key + ruleList.get(i).getStr("value");
			}
			cache.hset(Constant.R_PRE+"WEIXIN:MESSAGE:RULE", key,getReplyCache(ruleList.get(i).getInt("id")));
		}
	}
}
